package ua.tach.shortl.logic;

import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.Texture;

public class Link {
	public static Texture texture;
	public static Mesh mesh;
	private Switch[] sw = new Switch[4];
	
	protected Point index;
	
	public Link (Point ind) {
		index = new Point(ind);
		for(int i=0;i<4;++i)
			sw[i]= Switch.NULL;
	}

	public Link () {
		for(int i=0;i<4;++i)
			sw[i]= Switch.NULL;
	}

	public Switch getSw (int dir) {
		if (sw[dir] == Switch.NULL )
			sw[dir]= new Switch(this, dir);
		return sw[dir];
	}
	
	// Updating switches and semaphores
	public void update () {
		
	}
	
	public Rail getNext(int dir) {
		System.out.println("Chk dir " + dir);
		if (sw[dir] == Switch.NULL ) return Rail.NULL;
		switch (dir) {
		case 0: // +X
			return sw[2].getRail();
		case 1: // +Y
			return sw[3].getRail();
		case 2: // -X
			return sw[0].getRail();
		default: // -Y
			return sw[1].getRail();
		}
	}
	
	public boolean isFree(int dir) {
		return sw[dir].isFree();
	}
	
	public void addRail (int dir, Rail r, boolean railDir) {
		if (sw[dir] == Switch.NULL ) {
			sw[dir]= new Switch(this, dir);
		}
		sw[dir].addRail(r, railDir);
		
		// Check semaphors on rail add
		for ( int i = 0; i<4 ; ++i) {
			int semt = getDesiredSem(i);
			if (sw[i].getSemType() != semt) {
				System.out.println("Set " + sw[i]+ " type "+ semt);
				sw[i].setSemaphor(semt);
			}
		}
	}
	
	private int getDesiredSem( int i) {
		// Possible types:
		// 0 - no semaphors
		// 1 - switch
		// 2 - light
		// 3 - tupik
		switch ( sw[i].getRailCount() ) {
		case 1:
			if (sw[(i+2)%4].getRailCount() == 1 && sw[(i+3)%4].getRailCount() == 0 && sw[(i+1)%4].getRailCount() == 0 
					&& sw[(i+2)%4].getRail().getRailDir(sw[(i+2)%4]) != 2) // only on round rails
				return 2;
			else return 0;
		case 2:
			return 1;
		default:
			if (sw[(i+2)%4].getRailCount() > 0 ) {
				if (sw[i] == Switch.NULL ) sw[i]= new Switch(this, i);
				return 3;
			}
			return 0;	
		} 
	}
	
	public void render(GL10 gl) {
//		texture.bind();
//		gl.glPushMatrix();
//		gl.glTranslatef(index.x, 0, index.y);
//		gl.glScalef(0.2f, 0.2f, 0.2f);
//		mesh.render(GL10.GL_TRIANGLES);
//		gl.glPopMatrix();
		
		for( Switch s : sw)
			s.render(gl);
	}
	
	@Override public String toString() {
	    StringBuilder result = new StringBuilder();
	    result.append("Link[" + index.x + ":" + index.y+"]");
	    return result.toString();
	  }

}
